import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/ModernAdminLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: { title: '仪表盘', pageTitle: '仪表盘', pageSubtitle: '掌握关键运营概况' }
      },
      {
        path: 'products-integrated',
        name: 'ProductIntegratedList',
        component: () => import('@/views/ProductIntegrated/List.vue'),
        meta: { title: '产品管理', pageTitle: '产品管理', pageSubtitle: '集成变体列表' }
      },
      {
        path: 'products-integrated/create',
        name: 'ProductIntegratedCreate',
        component: () => import('@/views/ProductIntegrated/Edit.vue'),
        meta: { title: '创建产品', pageTitle: '创建产品', pageSubtitle: '填写详细信息并发布' }
      },
      {
        path: 'products-integrated/:id/edit',
        name: 'ProductIntegratedEdit',
        component: () => import('@/views/ProductIntegrated/Edit.vue'),
        meta: { title: '编辑产品', pageTitle: '编辑产品', pageSubtitle: '更新已有产品信息' }
      },
      {
        path: 'categories',
        name: 'CategoryList',
        component: () => import('@/views/Category/List.vue'),
        meta: { title: '分类管理', pageTitle: '分类管理', pageSubtitle: '维护产品分类结构' }
      },
      {
        path: 'carousels',
        name: 'CarouselList',
        component: () => import('@/views/Carousel/List.vue'),
        meta: { title: '轮播图管理', pageTitle: '轮播图管理', pageSubtitle: '配置首页展示内容' }
      },
      {
        path: 'contact-messages',
        name: 'ContactMessageList',
        component: () => import('@/views/ContactMessage/List.vue'),
        meta: { title: '客户留言', pageTitle: '客户留言', pageSubtitle: '处理用户反馈与咨询' }
      },
      {
        path: 'customers',
        name: 'CustomerList',
        component: () => import('@/views/Customer/List.vue'),
        meta: { title: '客户管理', pageTitle: '客户管理', pageSubtitle: '管理所有注册客户' }
      },
      {
        path: 'orders',
        name: 'OrderList',
        component: () => import('@/views/Order/List.vue'),
        meta: { title: '订单管理', pageTitle: '订单管理', pageSubtitle: '查看与处理订单状态' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)

  if (requiresAuth && !authStore.isAuthenticated) {
    // 需要登录但未登录，跳转到登录页
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.name === 'Login' && authStore.isAuthenticated) {
    // 已登录访问登录页，跳转到首页
    next({ name: 'Dashboard' })
  } else if (requiresAuth && authStore.isAuthenticated && !authStore.user) {
    // 已登录但没有用户信息，重新获取用户信息并检查权限
    try {
      const hasPermission = await authStore.fetchUserInfo()
      if (!hasPermission) {
        // 没有管理员权限，跳转到登录页
        next({ name: 'Login' })
        return
      }
    } catch (error) {
      // 获取用户信息失败，跳转到登录页
      next({ name: 'Login' })
      return
    }
    next()
  } else {
    next()
  }
})

export default router
